<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\User;

use Think\Log;
use Think\Model;

class User extends \Service\Common\BaseModel
{
    protected $name = 'user';
    
    protected $vip_level_label =[
                 "普通会员",
                 "会长",
                 "超级会长",
                 "VIP1",
                 "VIP2",
                 "VIP3",
    ];
    
    protected $agent_level_label =[
			    "无",
			    "县级代理",
			    "市级代理",
    ];
    
    public function formatCallback($data)
    {
    	list($total_performance,) = O('data')->getTeam('','', $data['user.mobile']);
    	$referer_name = $this->getUserName($data['user.referer_id']);
        $nickname = $this->getNickName($data['user.referer_id']);
    	return [
    	   'user.total_performance'=>$total_performance,//销售业绩
    	   'user.referer_name'=>$referer_name,//推荐人用户名
    	   'user.referer_nickname'=>$nickname,//推荐人昵称
//    	   'user.referer_nickname'=> '<img style="width: 40px;" src="https://inews.gtimg.com/newsapp_ls/0/10945873904_294195/0" >',//推荐人昵称
    	];
    }
    
    public function getUserName($uid)
    {
    	$username = M('ucenter_member')->where([
    			'id' => $uid
    			])->getField('username');
    	return $username;
    }

    public function getNickName($uid)
    {
        $username = M('user')->where([
            'uid' => $uid
        ])->getField('nickname');
        return $username;
    }
    
    public function chenckmMobile($phone,$uid)
    {
    	$count = M('ucenter_member')->where([
    			'mobile'=>$phone,
    			'id'=>['neq',$uid]])->count();
    	if ($count > 0) {
    		throw new \Exception("手机号重复");
    	}
    	M('user')->where(array('uid' => $uid))->save(['mobile'=>$phone]);
    	M('ucenter_member')->where(array('id' => $uid))->save(['mobile'=>$phone]);
    	return true;
    }
    
    public function editMobile($uid, $mobile)
    {
    	$count = M('ucenter_member')->where([
    			'mobile'=>$mobile,
    			'id'=>['neq',$uid]])->count();
    	if ($count > 0) {
    		throw new \Exception("手机号重复");
    	}
    	$update = M('ucenter_member')->where([
    			      'id'=>$uid
    			 ])->save([
    			 	  'mobile' =>$mobile
    			 		]);
    	if($update === false){
    		throw new \Exception("修改手机号失败");
    	}
    	return true;
    }
    
    //我的直属下级
    public function getUserDirectlyUnder($login_uid, $uid)
    {
        if ($uid && !$this->where(['referer_id' => $login_uid, 'uid' => $uid])->find()) {
            throw new \Exception("无效的用户id");
        }

        $list = $this->where([
            'referer_id' => $uid ?: $login_uid
        ])->order('uid asc')->select();
        return $this->format($list) ?: [];
    }

    //退出
    public function logout($uid)
    {
        $this->unbindOauth();
    }

    //获取授权绑定用户的token
    public function getTokenByOauth($uid)
    {
        $oauth_info = O('Kcdns\Service\User')->currentOauth();
        if (!$oauth_info) {//未授权
            return '';
        }

        $result = M('oauth')->where(['openid' => $oauth_info['openid']])->find();
        if (!$result) {
            throw new \Exception("没有授权记录");
        }

        //已绑定
        if ($user_id = $result['user_id']) {
            return $this->genApiToken($user_id);
        }

        //未绑定 未登录
        if (!$uid) {
            return '';
        }

        //未绑定 已登录 自动绑定
        $this->bindOauth($uid);

        return $this->genApiToken($uid);
    }

    protected function unbindOauth()
    {
        $oauth_info = O('Kcdns\Service\User')->currentOauth();
        if (!$oauth_info) {
            return false;
        }

        $where = array(
            'openid' => $oauth_info['openid'],
            'type' => $oauth_info['type']
        );
        $update = M('Oauth')->where($where)->save(array('user_id' => 0));
        if ($update === false) {
            throw new \Exception("解绑用户失败");
        }
    }

    protected function bindOauth($uid)
    {
        $oauth_info = O('Kcdns\Service\User')->currentOauth();
        if (!$oauth_info) {
            return false;
        }

        $where = array(
            'openid' => $oauth_info['openid'],
            'type' => $oauth_info['type']
        );
        M('Oauth')->where([
            'type' => $oauth_info['type'],
            'user_id' => $uid
        ])->save(array('user_id' => 0));
        $update = M('Oauth')->where($where)->save(array('user_id' => $uid));
        if ($update === false) {
            throw new \Exception("绑定用户失败");
        }
    }

    //获取下级用户
    public function getSubUserList($uid, $level = 1, $page_num = 1, $page_size = 5)
    {
        $level = $level == 1 ? '' : $level;
        //$where = ["referer{$level}_id" => $uid];
        $where = ["uid" => $uid];
        $list = (array)$this->where($where)->order('uid desc')->page($page_num, $page_size)->select();
        $count = $this->where($where)->count();
        return [
            $this->format($list),
            $page_count = $count,
            $page_total = ceil($count / $page_size),
        ];
    }

    //财务
    public function finance($login_info)
    {
        $uid = $login_info['uid'];
        //订单统计
        $order_status_num = OE('order')->getStatusNum($uid);

        $result = [
            'balance' => $login_info['balance'],
            'total_point' => $login_info['total_point'],
            'total_order' => $order_status_num['total_order'],
            'order_unpaid_num' => $order_status_num['order_unpaid_num'],
            'order_paid_num' => $order_status_num['order_paid_num'],
            'order_send_num' => $order_status_num['order_send_num'],
            'order_receive_num' => $order_status_num['order_receive_num'],
            'total_red_packets' => $login_info['total_red_packets'],
            'service_center_income' => $order_status_num['order_invite_num'],
        ];

        $income = [
            'red_packets' => $login_info['red_packets'],
            'goods_income' => M('commission_log')->where(['settle_status' => 1, 'uid' => $uid, 'type' => \Service\User\CommissionLog::COMMISSION_TYPE_SALE1])->sum('money') ?: '0.00',
            'service_income' => M('commission_log')->where(['settle_status' => 1, 'uid' => $uid, 'type' => \Service\User\CommissionLog::COMMISSION_TYPE_SALE2])->sum('money') ?: '0.00',
            'jinpai_income' => M('commission_log')->where(['settle_status' => 1, 'uid' => $uid, 'type' => \Service\User\CommissionLog::COMMISSION_TYPE_JINGPAI])->sum('money') ?: '0.00',
            'zuanshi_income' => M('commission_log')->where(['settle_status' => 1, 'uid' => $uid, 'type' => \Service\User\CommissionLog::COMMISSION_TYPE_ZUANSHI])->sum('money') ?: '0.00',
            'huangguan_income' => M('commission_log')->where(['settle_status' => 1, 'uid' => $uid, 'type' => \Service\User\CommissionLog::COMMISSION_TYPE_HUANGGUAN])->sum('money') ?: '0.00',
            'huangguandashi_income' => M('commission_log')->where(['settle_status' => 1, 'uid' => $uid, 'type' => \Service\User\CommissionLog::COMMISSION_TYPE_HUANGUANDASHI])->sum('money') ?: '0.00',
            'zhizun_income' => M('commission_log')->where(['settle_status' => 1, 'uid' => $uid, 'type' => \Service\User\CommissionLog::COMMISSION_TYPE_ZHIZUN])->sum('money') ?: '0.00',
            'wuxing_income' => M('commission_log')->where(['settle_status' => 1, 'uid' => $uid, 'type' => \Service\User\CommissionLog::COMMISSION_TYPE_WUXING])->sum('money') ?: '0.00',
        ];
        $result = array_merge($result, $income);
        $result['total_income'] = array_sum(array_values($income));

        return $result;
    }

    //修改支付密码
    public function changePayPassword($data, $uid)
    {
        $this->checkOldPayPassword($uid, $data['old_password']);
        $this->where([
            'uid' => $uid
        ])->save([
            'pay_password' => $this->encryptPassword($data['pay_password'], DATA_ENCRYPT_KEY),
            'update_time' => date('Y-m-d H:i:s')
        ]);

        return true;
    }

    //验证旧支付密码
    public function checkOldPayPassword($uid, $old_password)
    {
        $user = $this->getUserInfo($uid);
        if ($this->encryptPassword($old_password, DATA_ENCRYPT_KEY) != $user['pay_password']) {
            throw new \Exception("旧支付密码不正确");
        }
        return true;
    }

    //验证旧密码
    public function checkOldPassword($uid, $old_password)
    {
        $user = M('ucenter_member')->find($uid);
        if (!$user) {
            throw new \Exception("无效的用户");
        }

        if ($this->encryptPassword($old_password, DATA_ENCRYPT_KEY) != $user['password']) {
            throw new \Exception("旧密码不正确");
        }
        return true;
    }

    //找回密码
    public function findPwd($data)
    {
        if ($data['new_password'] != $data['confirm_password']) {
            throw new \Exception("两次密码不一致");
        }

        $info = M('ucenter_member')->where(['mobile' => $data['mobile']])->find();
        if (!$info) {
            throw new \Exception("该手机号不存在");
        }

        $checkCode = O('sms')->checkCode($data['mobile'], $data['code'], 'findPwd');
        if ($checkCode === false) {
            throw new \Exception("短信验证码不正确");
        }

        M('ucenter_member')->save([
            'id' => $info['id'],
            'password' => $this->encryptPassword($data['new_password'], DATA_ENCRYPT_KEY)
        ]);
    }

    //修改密码
    public function changePassword($data, $uid)
    {
        if ($data['new_password'] != $data['confirm_password']) {
            throw new \Exception("两次密码不一致");
        }

        $this->checkOldPassword($uid, $data['old_password']);

        M('ucenter_member')->save([
            'id' => $uid,
            'password' => $this->encryptPassword($data['new_password'], DATA_ENCRYPT_KEY)
        ]);

        return true;
    }

    //绑定老用户
    public function bindWx($data, $uid)
    {
        $model = new Model();
        $this->checkOldPassword($uid, $data['old_password']);
        $old_user_data = $model
            ->table('__UCENTER_MEMBER__')
            ->where(['username' => $data['old_username']])
            ->find();
        if (!$old_user_data) {
            throw new \Exception("老用户是无效的用户");
        }
        if($old_user_data['id'] == $uid){
            throw new \Exception("请勿填写自己本人");
        }
        //检查老会员密码
        if ($this->encryptPassword($data['confirm_password'], DATA_ENCRYPT_KEY) != $old_user_data['password']) {
            throw new \Exception("老会员密码不正确");
        }
        $this->checkOldPassword($old_user_data['id'], $data['confirm_password']);

        try {

            $model->startTrans();
            //绑定
            $result = $model->table('__OAUTH__')->where(['user_id' => $uid])->save([
                'user_id' => $old_user_data['id'],
                'update_time' => date('Y-m-d H:i:s')
            ]);
            $my_user_data = M('user')->where(['uid' => $uid])->find();
            $old_user_save = [
                'nickname' => $my_user_data['nickname'],
                'avatar_url' => $my_user_data['avatar_url'],
                'mobile' => '',
            ];
            Log::w_log("######".json_encode($old_user_save));
            $user_update = M('user')->where(['uid' => $old_user_data['id']])->save($old_user_save);
            if(!$user_update) throw new \Exception("更新老会员数据失败");
            M('ucenter_member')->where(['id' => $old_user_data['id']])->save(['mobile' => '']);

            $model->commit();
        } catch (\Exception $e) {
            $model->rollback();
            throw new \Exception($e->getMessage());
        }

        return true;
    }

    //完善用户信息
    public function fillUserInfo($data, $uid)
    {
        if($data['mobile']){
            $user_data = M('user')->where(['mobile' => $data['mobile']])->find();
            if($user_data && $user_data['uid'] != $uid) throw new \Exception('此手机号已注册');
        }
        $user = $this->getUserInfo($uid);

        //已填过不可修改
        $fileds = [
            'mobile',
            'real_name',
            'id_no',
            'area',
            'address',
            'email',
            'bank_type',
            'bank_no',
        ];
        foreach ($fileds as $val) {
            if ($user[$val]) {
                unset($data[$val]);
            }
        }
        try {
            $this->startTrans();

            $update = $this->where([
                'uid' => $uid
            ])->save(array_merge(
                $data,
                [
                    'update_time' => date('Y-m-d H:i:s'),
                ]
            ));
            if ($update === false) {
                throw new \Exception("用户更新失败");
            }
            $center_data = [];
            if ($data['email']) $center_data['email'] = $data['email'];
            if ($data['mobile']) $center_data['mobile'] = $data['mobile'];

           /* $update = M('ucenter_member')->where(['id' => $uid])->save($center_data);
            if ($update === false) {
                throw new \Exception("邮箱更新失败");
            }*/

            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }

        return true;
    }

    //验证支付密码
    public function checkPayPassword($uid, $pay_password)
    {
        $user = $this->getUserInfo($uid);
        if (!$user['pay_password'] || $this->encryptPassword($pay_password, DATA_ENCRYPT_KEY) != $user['pay_password']) {
            throw new \Exception("支付密码不正确");
        }
        return true;
    }
    
    
    //修改密码
    public function reset($uid, $data = array())
    {
    	if (isset($data['ucenter_member.password']) && $data['ucenter_member.password'] != '') {	
    		$password = $this->resetPwd($uid,$data['ucenter_member.password']);
    	}
    	if (isset($data['user.pay_password']) && $data['user.pay_password'] != '') {
    		$this->resetPayPwd($uid,$data['user.pay_password']);
    	}
    	return true;
    }

    //重置支付密码
    public function resetPayPwd($uid, $password = '')
    {
        $password = $password ?: '123456';
        $this->where(['uid' => $uid])->save([
            'pay_password' => $this->encryptPassword($password, DATA_ENCRYPT_KEY)
        ]);     
        return $password;
    }

    //重置登录密码
    public function resetPwd($uid, $password = '')
    {
        $password = $password ?: '123456';
        $password = (new \Kcdns\User\Api\UserApi())->resetPwd($uid, $password);
        return $password;
    }

    //用户详情
    public function getDetail($uid)
    {
        $result = $this
            ->table('__USER__ a')
            ->join('__UCENTER_MEMBER__ b on b.id=a.uid')
            ->where(['a.uid' => $uid])
            ->find();

        if (!$result) {
            throw new \Exception("无效的用户");
        }
        //$vip_array = ["普通会员","VIP会员","合伙人","一星合伙人","二星合伙人","三星合伙人","四星合伙人","五星合伙人"];
        $vip_array =$this->vip_level_label;
        $agent_array = $this->agent_level_label;
        $result['level_text'] = $vip_array[$result['vip_level']];
        $result['agent_level_text'] = $agent_array[$result['agent_level']];
        if (!$result['invite_code']) {
            while (true) {
                $invite_code = O('util')->rand(6);
                if (!$this->where(['invite_code' => $invite_code])->find()) {
                    $this->save([
                        'uid' => $result['uid'],
                        'invite_code' => $invite_code
                    ]);
                    $result['invite_code'] = $invite_code;
                    break;
                }
            }
        }

        $url = "http://{$_SERVER['HTTP_HOST']}/wap/index/wxReg?inviteCode={$result['invite_code']}";
        $result = $this->format($result);
        $avatar_url = preg_match('/^http(s)?:\/\/.+/i', $result['avatar_url']) ? $result['avatar_url'] : "http://{$_SERVER['HTTP_HOST']}" . $result['avatar_url'];
//        $result['invite_qrcode'] = "http://qr.liantu.com/api.php?text={$url}&logo={$avatar_url}";
//        $result['invite_qrcode'] = O('util')->logQrcode($url, $avatar_url);
        $result['invite_qrcode'] = O('util')->qrcode($url);
        return $result;
    }

    //用户单表信息
    public function getUserInfo($uid, $field = 'uid')
    {
        $user = $this->where([$field => $uid])->find();
        if (!$user) {
            throw new \Exception("无效的用户");
        }
        if ($user['is_frozen']) {
        	throw new \Exception("冻结账号，禁止登录");
        }
        return $user;
    }

    //注册
    public function register($data)
    {
        if ($data['password'] != $data['confirm_password']) {
            throw new \Exception('两次密码不一致');
        }

        $user = M('ucenter_member')->where([
            'mobile' => $data['mobile'],
        ])->find();
        if ($user) {
            throw new \Exception("该手机号已存在");
        }

        /*$checkCode = O('sms')->checkCode($data['mobile'], $data['code'], 'register');
        if ($checkCode === false) {
            throw new \Exception("短信验证码不正确");
        }*/

        $referer_id = 0;
        $referer2_id = 0;
        $referer_username = '';
        if ($data['referer']) {
            if (preg_match('/^\d{6}$/', $data['referer'])) {
                $result = $this
                    ->field('a.*,b.referer_id,b.referer2_id')
                    ->table('__UCENTER_MEMBER__ a')
                    ->join('__USER__ b on b.uid=a.id')
                    ->where([
                        'b.invite_code' => $data['referer']
                    ])
                    ->find();
            } else {
                $field = $this->getLoginType($data['referer'], 2);
                $result = $this
                    ->field('a.*,b.referer_id,b.referer2_id')
                    ->table('__UCENTER_MEMBER__ a')
                    ->join('__USER__ b on b.uid=a.id')
                    ->where([
                        'a.' . $field => $data['referer']
                    ])
                    ->find();
            }

            if (!$result) {
                \KCSLog::Debug(var_export($data, true));
                throw new \Exception('该1级推荐人不存在');
            }
            $referer_id = $result['id'];
            $referer_username = $result['username'];
            $referer2_id = $result['referer_id'];
        }

        $uid = 0;
        try {
            //        $username = substr(md5(DATA_ENCRYPT_KEY . '|' . $data['mobile']), 8, 16);
            $username = "qch".$this->genUsername();
            $uid = OE('Kcdns\Service\User')->register($username, $data['password'], '', false, '', $data['mobile']);

            $this->startTrans();
            //更新推荐人
            $update = $this->where([
                'uid' => $uid
            ])->save([
                'update_time' => date('Y-m-d H:i:s'),
                'referer_id' => $referer_id,
                'referer2_id' => $referer2_id,
                'pay_password' => $this->encryptPassword($data['password'], DATA_ENCRYPT_KEY),

            ]);
            if ($update === false) {
                throw new \Exception("更新推荐人失败");
            }

            /*if (SPEED_API_OPEN) {
                //加速中心同步注册
                $api_data = [
                    'company' => SPEED_API_CLIENT,
                    'req_time' => time(),
                    'username' => $username,
                    'referer' => $referer_username,
                ];
                $response = OE('util')->curl(SPEED_API_HOST . '/Wap/api/register', array_merge($api_data, [
                    'sign' => $this->genSign($api_data)
                ]));
                $result = json_decode($response, true);
                if ($result['status'] != 1) {
                    throw new \Exception("同步注册失败,请联系管理员");
                }
            }*/

            $this->bindOauth($uid);

            //生成api_token
            $api_token = $this->genApiToken($uid);
            $this->commit();

            O('sms')->send($data['mobile'], "\"{$data["mobile"]}\"", '', 'system');
            return $api_token;
        } catch (\Exception $e) {
            $this->rollback();
            M('ucenter_member')->delete($uid);
            $this->where(['uid' => $uid])->delete();
            throw new \Exception($e->getMessage());
        }
    }

    //注册
    public function register2($data)
    {
        $referer_id = 0;
        $referer2_id = 0;
        $referer_username = '';
       /* if ($data['invite_code']) {
            $result = $this
                ->field('a.*,b.referer_id,b.referer2_id')
                ->table('__UCENTER_MEMBER__ a')
                ->join('__USER__ b on b.uid=a.id')
                ->where([
                    'b.invite_code' => $data['invite_code']
                ])
                ->find();

//            Log::w_log('参数：'.json_encode($data));

            if (!$result) {
                $ret = array('code' => -1, 'msg' => '该1级推荐人不存在');
                return $ret;
            }
            $referer_id = $result['id'];
            $referer_username = $result['username'];
            $referer2_id = $result['referer_id'];
        } else {
            $ret = array('code' => -1, 'msg' => '邀请人code不能为空');
            return $ret;
        }*/

        $uid = 0;
        try {
            //        $username = substr(md5(DATA_ENCRYPT_KEY . '|' . $data['mobile']), 8, 16);
            $username = "qch".$this->genUsername();
            $uid = OE('Kcdns\Service\User')->register($username, $data['password'], '', false, '', '');

            $this->startTrans();
            //更新推荐人
            $avatar_url = OE('file')->downImages($data['head']);
            $update = $this->where([
                'uid' => $uid
            ])->save([
                'update_time' => date('Y-m-d H:i:s'),
                'referer_id' => $referer_id,
                'referer2_id' => $referer2_id,
                'pay_password' => $this->encryptPassword($data['password'], DATA_ENCRYPT_KEY),
                'nickname' => $data['nickname'],
                'avatar_url' => $data['head'],
                'vip_level' => 1

            ]);
            if ($update === false) {
                $ret = array('code' => -1, 'msg' => '更新推荐人失败');
                return $ret;
            }

            /*if (SPEED_API_OPEN) {
                //加速中心同步注册
                $api_data = [
                    'company' => SPEED_API_CLIENT,
                    'req_time' => time(),
                    'username' => $username,
                    'referer' => $referer_username,
                ];
                $response = OE('util')->curl(SPEED_API_HOST . '/Wap/api/register', array_merge($api_data, [
                    'sign' => $this->genSign($api_data)
                ]));
                $result = json_decode($response, true);
                if ($result['status'] != 1) {
                    $ret = array('code' => -1, 'msg' => '同步注册失败,请联系管理员');
                    return $ret;
                }
            }*/

            $this->bindOauth($uid);

            //生成api_token
            $api_token = $this->genApiToken($uid);
            $this->commit();
            $user_detail = $this->where(array('uid' => $uid))->find();
            $ret = array('code' => 0, 'data' => array('api_token' => $api_token, 'invite_code' => $user_detail['invite_code']));
            return $ret;
        } catch (\Exception $e) {
            $this->rollback();
            M('ucenter_member')->delete($uid);
            $this->where(['uid' => $uid])->delete();
            $ret = array('code' => -1, 'msg' => '注册失败');
            return $ret;
        }

    }


    public function register3($data)
    {
        $referer_id = $data['referer_id'];
        $referer2_id = 0;
        $uid = 0;
        try {
            //        $username = substr(md5(DATA_ENCRYPT_KEY . '|' . $data['mobile']), 8, 16);
            $username = "eye_".$this->genUsername();
            $uid = OE('Kcdns\Service\User')->register($username, '123456', '', false, '', '');

            $this->startTrans();

            $update = $this->where([
                'uid' => $uid
            ])->save([
                'update_time' => date('Y-m-d H:i:s'),
                'referer_id' => $referer_id,
                'referer2_id' => $referer2_id,
                'pay_password' => $this->encryptPassword('123456', DATA_ENCRYPT_KEY),
                'nickname' => '',
                'avatar_url' => '',
                'openid' => $data['openid'],
                'vip_level' => 0

            ]);
            if ($update === false) {
                $ret = array('code' => -1, 'msg' => '更新用户信息失败');
                return $ret;
            }



            //生成api_token
            list($api_token, $expire_time) = $this->genApiToken($uid);
            $this->commit();
            $user_detail = $this->where(array('uid' => $uid))->find();
            $ret = array(
                'code' => 0,
                'data' =>
                    array(
                        'api_token' => $api_token,
                        'expire_time' => $expire_time,
                        'invite_code' => $user_detail['invite_code'],
                        'username' => $username,
                        'openid' => $data['openid'],
                        'uid' => $uid,
                    )
            );
            return $ret;
        } catch (\Exception $e) {
            $this->rollback();
            M('ucenter_member')->delete($uid);
            $this->where(['uid' => $uid])->delete();
            $ret = array('code' => -1, 'msg' => '注册失败');
            return $ret;
        }

    }

    //获取同步登录地址
    public function getSynLoginUrl($uid,$go)
    {
        $username = M('ucenter_member')->where(['id' => $uid])->getField('username');
        if (!$username) {
            throw new \Exception("无效的用户");
        }

        $api_data = [
            'company' => SPEED_API_CLIENT,
            'req_time' => time(),
            'openid' => $username,
        ];
        if($go == 1){
            return SPEED_API_HOST . '/?' . http_build_query(array_merge($api_data, [
                'sign' => $this->genSign($api_data)
            ]));
        }elseif($go == 2){
            return SPEED_API_HOST_KL . '/H5/signLogin?' . http_build_query(array_merge($api_data, [
                'sign' => $this->genSign($api_data)
            ]));
        }

    }

    //生成签名
    public function genSign($data)
    {
        return md5(join('', array_values($data)) . SPEED_API_KEY);
    }

    //生成用户名
    public function genUsername()
    {
        while (true) {
            $username = O('util')->rand(8, 1, '1');
            $user = M('ucenter_member')->where(['username' => $username])->find();
            if (!$user) {
                return $username;
            }
            break;
        }
    }

    public function getInviteCode(){
        while (true) {
            $invite_code = O('util')->rand(6, 1, '1');
            $user = M('user')->where(['invite_code' => $invite_code])->find();
            if (!$user) {
                return $invite_code;
            }
            break;
        }
    }

    //登录
    public function login($username, $password)
    {
        $uid = (new \Kcdns\User\Api\UserApi())->login($username, $password, $this->getLoginType($username, 1));
        if ($uid <= 0) {
            throw new \Exception('用户名或密码不正确');
        }

        try {
            $this->getUserInfo($uid);
        } catch (\Exception $e) {
            throw new \Exception('禁止登录');
        }

        $this->bindOauth($uid);

        return $this->genApiToken($uid);
    }

    //微信登录
    public function wxLogin($openid)
    {
        $bind_data=  M('oauth')->where(array('openid' => $openid))->find();

        if(!$bind_data){
            throw new \Exception('此微信用户未绑定');
        }
        return $this->genApiToken($bind_data['user_id']);
    }

    //生成登录token
    public function genApiToken($uid)
    {
        $api_token = O('util')->encodeJWT([
            'uid' => $uid,
            'expire_time' => $expire_time = time() + 30 * 24 * 3600
        ]);

        $insert_id = M('api_token')->add([
            'uid' => $uid,
            'token' => $api_token,
            'expire_time' => date('Y-m-d H:i:s', $expire_time),
            'create_time' => date('Y-m-d H:i:s'),
        ]);
        if (!$insert_id) {
            throw new \Exception('生成api_token失败');
        }

        return [$api_token, $expire_time];
    }

    //获取登录方式
    public function getLoginType($username, $return_type = 0)
    {
        //1-用户名，2-邮箱，3-手机
        if (preg_match('/^1\d{10}$/', $username)) {
            $login_type = 3;
            $login_field = 'mobile';
        } else if (preg_match('/^\w+@\w+\.\w+$/', $username)) {
            $login_type = 2;
            $login_field = 'email';
        } else {
            $login_type = 1;
            $login_field = 'username';
        }

        switch ($return_type) {
            case 1:
                return $login_type;
            case 2:
                return $login_field;
            default:
                return [$login_type, $login_field];
        }
    }

    //解码token
    public function decodeToken($token)
    {
        $result = O('util')->decodeJWT($token);
        if (!(($uid = $result['uid']) && $result['expire_time'] && $result['expire_time'] >= time())) {
            throw new \Exception('无效的token');
        }
        return $uid;
    }

    // 加密支付密码
    public function encryptPassword($str, $key = 'ThinkUCenter')
    {
        return '' === $str ? '' : md5(sha1($str) . $key);
    }

    //获取推荐人tree
    public function getRefererTree($uid, $count = 0, $manage_level = 0, &$referer_tree = [], $is_first = true)
    {
        static $current_level = 0;
        static $tree_ids = [];
        if ($is_first) {
            $current_level = 0;
            $tree_ids = [];
        }

        if (!$uid) {
            return $referer_tree;
        }

        $user = $this->where(['uid' => $uid])->find();
        if ($user['referer_id']) {
            $referer = $this->where(['uid' => $user['referer_id']])->find();
            $referer_tree[] = $referer;

            if (isset($tree_ids[$referer['uid']])) {
                throw new \Exception("关系树死循环");
            }
            $tree_ids[$referer['uid']] = $referer['uid'];

            //级数控制
            $current_level++;
            if ($count && $current_level == $count) {
                return $referer_tree;
            }

            //管理级别控制
            if ($manage_level && $manage_level == $referer['vip_level']) {
                return $referer_tree;
            }

            $this->getRefererTree($referer['uid'], $count, $manage_level, $referer_tree, $is_first = false);
        }

        return $referer_tree;
    }

    public function format($list)
    {
        if (!$list) {
            return $list;
        }

        $is_one = count($list) == count($list, 1);
        $list = $is_one ? [$list] : $list;

        foreach ($list as &$row) {
            if (!$row['avatar_url']) {
                $row['avatar_url'] = '/H5/images/tx.jpg';
            }

            $sex_label = ['男', '女'];
            $row['sex_label'] = $sex_label[$row['sex']];

            if ($row['area']) {
                $row['area_label'] = O('common')->getAreaLabel($row['area']);
            }

            if ($row['bank_type']) {
                $bank_list = O('common')->getBankList();
                $row['bank_type_label'] = $bank_list[$row['bank_type']];
            }
            
           // $level = ["普通会员","VIP会员","合伙人","一星合伙人","二星合伙人","三星合伙人","四星合伙人","五星合伙人"];
            $level = $this->vip_level_label;
            if ($row['vip_level'] != '') {
            	$row['vip_level_label'] = $level[$row['vip_level']];
            }
        }
        return $is_one ? $list[0] : $list;
    }

    //获取用户所有上级关系
    protected function _getTopRefererRelationTree($referer_id, &$list = [], $is_first = true)
    {
        if (!$referer_id) {
            return $list;
        }

        $referer = $this->where([
            'uid' => $referer_id
        ])->find();
        //$vip_array = ["普通会员","VIP会员","合伙人","一星合伙人","二星合伙人","三星合伙人","四星合伙人","五星合伙人"];
        $vip_array = $this->vip_level_label;
        if ($referer) {
            $uid = $referer['uid'];
            $referer_id = $referer['referer_id'] ?: '';
            $list[] = [
                'id' => $uid,
                'pId' => $referer_id,
                'uid' => $uid,
                'referer_id' => $referer_id,
                'real_name' => $referer['real_name'] ?: '-',
                'vip_level' => $vip_array[$referer['vip_level']] ?: '-',
                'haschild' => (bool)$this->where([
                    'referer_id' => $uid
                ])->count()
            ];

            if ($referer_id) {
                $this->_getTopRefererRelationTree($referer['referer_id'], $list, false);
            }
        }

        if ($is_first) {
            krsort($list);
            $list = array_values($list);
            foreach ($list as $key => $row) {
                $list[$key]['level'] = $key;
            }
        }

        return $list;
    }

    //获取用户所有上级树
    public function getTopRefererRelationTree($uid)
    {
        $result = $this->_getTopRefererRelationTree($uid);
        $current_level = count($result);

        return [
            $current_level,
            [
                'list' => $result,
                'title' => [
                    [
                        'name' => '真实姓名',
                        'field' => 'real_name',
                    ],
                    [
                        'name' => '级别',
                        'field' => 'level',
                    ],
                    [
                        'name' => 'uid',
                        'field' => 'uid',
                    ],
                    [
                    'name' => '会员级别',
                    'field' => 'vip_level',
                    ],
                ]
            ]
        ];
    }

    //获取下级直属用户
    public function getUnderRelation($uid, $current_level = 0)
    {
        $list = $this
            ->where([
                'referer_id' => $uid,
            ])
            ->select();

        $result = [];
        //$vip_array = ["普通会员","VIP会员","合伙人","一星合伙人","二星合伙人","三星合伙人","四星合伙人","五星合伙人"];
        $vip_array = $this->vip_level_label;
        foreach ($list as $key => $row) {
            $result[] = [
                'id' => $row['uid'],
                'pId' => $row['referer_id'],
                'uid' => $row['uid'],
                'referer_id' => $row['referer_id'],
                'real_name' => $row['real_name'] ?: '-',
                'mobile' => $row['mobile'] ?: '-',
                'level' => $current_level + 1,
                'vip_level' => $vip_array[$row['vip_level']] ?: '-',
                'haschild' => (bool)$this->where([
                    'referer_id' => $row['uid']
                ])->count()
            ];
        }
        return $result;
    }

    //升级vip级别
    public function upgradeVipLevel($uid)
    {
        $user = $this->getUserInfo($uid);
        $vip_level = $this->getVipLevel($user);
        if ($vip_level > $user['vip_level']) {
            $update = $this->where(['uid' => $uid])->save([
                'vip_level' => $vip_level,
                'update_time' => date('Y-m-d H:i:s')
            ]);

            if ($update === false) {
                throw new \Exception("升级vip级别失败");
            }
        }
    }

    //生成达标关系
    protected function genReachRelation($list)
    {
        M('reach_relation')->where(['id' => ['gt', 0]])->delete();
        $now = date('Y-m-d H:i:s');
        foreach ($list as $row) {
            $relation = array_merge([$row], $this->getRefererTree($row['uid']));
            $from_uid = $row['uid'];
            $from_level = $row['vip_level'];
            $uid = $from_uid;
            foreach ($relation as $parent) {
                $insert_id = M('reach_relation')->add([
                    'from_uid' => $from_uid,
                    'from_level' => $from_level,
                    'uid' => $uid,
                    'referer_uid' => (int)$parent['uid'],
                    'create_time' => $now,
                ]);
                if (!$insert_id) {
                    throw new \Exception("插入reach_relation失败");
                }
                $uid = $parent['uid'];
            }
        }
    }

    //升级所有用户会员等级
    public function upgradeAllVipLevel()
    {
        $list = (array)$this->order('total_contribution asc')->getField('uid,total_contribution,vip_level');
        try {
            $this->startTrans();

            //升级
            foreach ($list as $row) {
                $this->upgradeVipLevel($row['uid']);
            }

            //建立关系
            M('reach_relation')->where(['id' => ['gt', 0]])->delete();
            $now = date('Y-m-d H:i:s');
            foreach ($list as $row) {
                $relation = $this->getRefererTree($row['uid']);
                $from_uid = $row['uid'];
                $from_level = $row['vip_level'];
                $uid = $from_uid;
                foreach ($relation as $parent) {
                    $insert_id = M('reach_relation')->add([
                        'from_uid' => $from_uid,
                        'from_level' => $from_level,
                        'uid' => $uid,
                        'referer_uid' => (int)$parent['uid'],
                        'create_time' => $now,
                    ]);
                    if (!$insert_id) {
                        throw new \Exception("插入reach_relation失败");
                    }
                    $uid = $parent['uid'];
                }
            }
            //重新升级
            foreach ($list as $row) {
                $this->upgradeVipLevel($row['uid']);
            }
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }
    }

    //获取vip级别
    public function getVipLevel($user)
    {
        $list = get_list_config('VIP_LEVEL', true);
        $vip_level = 0;
        $commission_min_level = C('COMMISSION_MIN_LEVEL', null, 0);
        foreach ($list as $key => $row) {
        	//晋级最低级别
            if ($key > $commission_min_level && $vip_level < $commission_min_level) {
                continue;
            }

            //自身消费
            if ($row['self_buy']) {
                if (!($user['total_self_buy'] >= $row['self_buy'])) {
                    continue;
                }
            }

            //团队业绩
            if ($row['team']) {
                if (!($user['total_contribution'] >= $row['team'])) {
                    continue;
                }
            }

            //当月新增业绩
            $current_month = $row['current_month'];
            $row['reach_month'] AND $row['current_month'] = 0;
            if ($row['current_month']) {
                $sum = M('team_log')->where([
                    'uid' => $user['uid'],
                    'create_time' => [
                        ['egt', $start = date('Y-m-1 00.00:00')],
                        ['lt', date('Y-m-d H:i:s', strtotime('+1 month', strtotime($start)))],
                    ],
                ])->sum('performance');
                if (!($sum >= $row['current_month'])) {
                    continue;
                }
            }

            //达标月数
            if ($row['reach_month'] && $current_month) {
                $subQuery = M('team_log')->where([
                    'uid' => $user['uid'],
                ])->group('left(create_time,7)')->having("sum(performance) > $current_month")->select(false);
                $count = $this->table("$subQuery a")->count();
                if (!($count >= $row['reach_month'])) {
                    continue;
                }
            }

            //下级达标人数
            if ($row['sub_level']) {
                /*$count = M('reach_relation')->distinct('referer_uid,uid')->where([
                    'referer_uid' => $user['uid'],
                    'from_level' => $key - 1,
                ])->count();*/
                $s = $key - 1;
                $count = M('user')->where([
                    'referer_id' => $user['uid'],
                    'vip_level' => ['egt',$s],
                ])->count();
                if (!($count >= $row['sub_level'])) {
                    continue;
                }
            }

            $vip_level = $key;
        }
        return $vip_level;
    }

    //升级代付级别
    public function upgradeLeaderLevel($uid)
    {
        $user = $this->getUserInfo($uid);
        $leader_level = $this->getLeaderLevel($user['total_remit']);
        if ($leader_level > $user['leader_level']) {
            $update = $this->where(['uid' => $uid])->save([
                'leader_level' => $leader_level,
                'is_leader' => 1,
                'update_time' => date('Y-m-d H:i:s')
            ]);
            if ($update === false) {
                throw new \Exception("升级代付级别失败");
            }
        }
    }

    //升级管理级别
    public function upgradeManageLevel($uid)
    {
        $user = $this->getUserInfo($uid);
        $manage_level = $this->getManageLevel($user['uid'], $user['total_contribution']);
        if ($manage_level > $user['manage_level']) {
            $update = $this->where(['uid' => $uid])->save([
                'manage_level' => $manage_level,
                'update_time' => date('Y-m-d H:i:s')
            ]);
            if ($update === false) {
                throw new \Exception("升级管理级别失败");
            }
        }
    }

    //获取代付级别
    public function getLeaderLevel($total_remit)
    {
        $list = get_list_config('LEADER_LEVEL', true);
        arsort($list);
        $leader_level = 0;
        foreach ($list as $row) {
            list($min, $max) = explode(',', trim($row['remit']));
            $min = $min ? $total_remit > $min : true;
            $max = $max ? $total_remit <= $max : true;
            if ($min && $max) {
                $leader_level = $row['type'];
                break;
            }
        }
        return $leader_level;
    }

    //获取管理级别
    public function getManageLevel($uid, $total_contribution)
    {
        $list = get_list_config('MANAGE_LEVEL', true);
        arsort($list);
        $manage_level = 0;
        foreach ($list as $row) {
            list($min, $max) = explode(',', trim($row['team']));
            $referer = $row['referer'];
            $under_number = $this->where(['referer_id' => $uid, 'manage_level' => ($row['type'] - 1)])->count();

            $min = $min ? $total_contribution > $min : true;
            $max = $max ? $total_contribution <= $max : true;
            $under_number = $referer ? $under_number >= $referer : true;
            if ($min && $max && $under_number) {
                $manage_level = $row['type'];
                break;
            }
        }
        return $manage_level;
    }

    //累计自身消费
    public function increaseSelfBuy($uid, $money)
    {
        $update = M('user')->save([
            'uid' => $uid,
            'total_self_buy' => ['exp', "total_self_buy+{$money}"]
        ]);
        if ($update === false) {
            throw new \Exception("自身消费累计更新失败");
        }

        //升级会员级别
        $this->upgradeVipLevel($uid);
//        $this->upgradeAllVipLevel();
    }

    public function user_import($xls_file)
    {
        if (!is_file($xls_file) || !in_array(strtolower(pathinfo($xls_file, PATHINFO_EXTENSION)), ['xls', 'xlsx'])) {
            throw new \Exception('无效的xls文件');
        }

        $result = OE('util')->readXsl($xls_file);
        unset($result[0]);
        $Model = new Model();
        try {

            $Model->startTrans();
            foreach ($result as $key => $row) {
                list($uid, $referer_id, $username, $password) = $row;
                $user_data = array(
                    'uid' => $uid,
                    'referer_id' => $referer_id,
                );
                $ucenter_data = array(
                    'id' => $uid,
                    'username' => $username,
                    'password' => $password,
                    'status' => 1,
                );
                $ret1 = $Model->table('__USER__')->add($user_data);
                $ret3 = $Model->table('__UCENTER_MEMBER__')->add($ucenter_data);
                if(!$ret1 || !$ret3){
                    throw new \Exception('导入数据失败：'.$uid);
                }
            }

            $Model->commit();
        } catch (\Exception $e) {
            $Model->rollback();
            throw new \Exception($e->getMessage());
        }
    }


    public function daoUser()
    {

        $model = new Model();
        $ding_uid = 4058;
        $result = [];
        $user_data =  $model->table('__USER__ as u')
            ->field('u.uid, u.total_contribution, u.total_self_buy, u.referer_id,
                 m.username, m.password, m1.username as re_username')
            ->join('__UCENTER_MEMBER__ as m on u.uid=m.id')
            ->join('__UCENTER_MEMBER__ as m1 on u.referer_id=m1.id')
            ->where([
                'm.id' => [['egt', $ding_uid],['elt', 4500]],
            ])
            ->select();



        foreach($user_data as &$item) {
            $uid = $item['referer_id'];
            while(true){
                $user = $model->table('__USER__')
                    ->where(['uid' => $uid])
                    ->find();
                if($user['uid'] == $ding_uid){
                    $result[] = $item;
                    break;
                }
                if(!$user){
                    break;
                }
                $uid = $user['referer_id'];
                Log::w_log("@@@@@@uid:".$uid);
            }

        }

        $file = fopen(ROOT_PATH .'Public/user666.xls', 'w');
        fwrite($file, "uid\tusername\tpassword\tre_username\treferer_id\t\n");

        foreach ($result as &$item) {
            fwrite($file, $item->uid."\t".$item->username."\t".$item->password."\t".$item->re_username."\t".$item->referer_id."\t\n");//这里写得不好，应该把所有文件内容组装到一个字符串中然后一次性写入文件。
        }

        fclose($file);

        echo "success";exit();
    }

    public function shellDaoUser()
    {
        $head = [
            "用户名",
            "密码",
            "推荐人用户名",
            "贡献值",
            "自身消费",
        ];

        $result = array();
        $model = new Model();
        $ding_uid = 7116;
        $result = [];
        $data =  $model->table('__USER__ as u')
            ->field('u.uid, u.total_contribution, u.total_self_buy, u.referer_id,
                 m.username, m.password, m1.username as re_username')
            ->join('__UCENTER_MEMBER__ as m on u.uid=m.id')
            ->join('__UCENTER_MEMBER__ as m1 on u.referer_id=m1.id')
            ->where([
                'm.id' => [['egt', $ding_uid]],
            ])
            ->select();

        foreach($data as &$item) {
            $uid = $item['referer_id'];
            while(true){
                $user = $model->table('__USER__')
                    ->where(['uid' => $uid])
                    ->find();
                if($user['uid'] == 3528){
                    $result[] = $item;
                    break;
                }
                if(!$user){
                    break;
                }
                $uid = $user['referer_id'];
            }

        }



        foreach ($result as $row) {
            $data[] = [
                $row['username'],
                $row['password'],
                $row['re_username'],
                $row['total_contribution'],
                $row['total_self_buy'],
                0,
            ];
        }

        Log::w_log("####### dao: ".json_encode($result));

        array_unshift($data, $head);
        $file = O('util')->writeXls($data, 'huiyuan11');
       return true;
    }

    public function testSubmit($uid, $param){
        $test = M('eyes_test')->where(['id' => $param['id']])->find();
        if(!$test) throw new \Exception('视力测试科目不存在');
        $user = M('user')->where(['uid' => $uid])->find();
        if($test['price']>$user['eyes_coupon']) throw new \Exception('护眼测试券不足');
        try {
            $this->startTrans();
            //更新提现状态
            $update = M('user')->where(['uid' => $uid])->save([
                'eyes_coupon' => ['exp', "eyes_coupon-{$test['price']}"],
                'update_time' => date('Y-m-d H:i:s'),
            ]);
            if ($update === false) {
                throw new \Exception("扣除视力测试券失败-1");
            }
            //资金记录
            $add = [
                'userid' => $uid,
                'type' => 0,
                'typeid' => 1,
                'taskid' => 0,
                'change_money' => $test['price'],
                'old_balance' => $user['eyes_coupon'],
                'new_balance' => $user['eyes_coupon']-$test['price'],
                'create_time' => date('Y-m-d H:i:s'),
                'remarks' => "视力测试-{$test['title']}扣除{$test['price']}张券",
            ];
            $flag = M('eyes_money_log')->add($add);
            if(!$flag) throw new \Exception("扣除视力测试券失败");
            $flag = M('eyes_task_log')->where(['taskid' => 6, 'userid' => $uid, 'record_date' => date('Y-m-d')])->find();
            if(!$flag) OE('user')->addEyesMoney($uid, 6);
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }
    }

    public function couponShareAdd($uid){
        try {
            $this->startTrans();
            $user = M('user')->where(['uid' => $uid])->find();
            $coupon_num = getConfigValue('GET_SHARE_COUPON_NUM');
            $update = M('user')->where(['uid' => $uid])->save([
                'eyes_coupon' => ['exp', "eyes_coupon+{$coupon_num}"],
                'update_time' => date('Y-m-d H:i:s'),
            ]);
            if ($update === false) {
                throw new \Exception("获得视力测试券失败-1");
            }
            //资金记录
            $add = [
                'userid' => $uid,
                'type' => 0,
                'typeid' => 0,
                'taskid' => 0,
                'change_money' => $coupon_num,
                'old_balance' => $user['eyes_coupon'],
                'new_balance' => $user['eyes_coupon']+$coupon_num,
                'create_time' => date('Y-m-d H:i:s'),
                'remarks' => "微信分享获得{$coupon_num}张券",
            ];
            $flag = M('eyes_money_log')->add($add);
            if(!$flag) throw new \Exception("获得视力测试券失败");

            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }
    }

    public function addEyesMoney($uid, $task_id){
        try {
            $this->startTrans();

            //任务查询
            $task = M('eyes_task')->where(['id' => $task_id])->find();
            if(!isset($task['id'])) throw new \Exception("任务不存在");
            $coupon_num = $task['taskprice'];
            $user = M('user')->where(['uid' => $uid])->find();
            $update = M('user')->where(['uid' => $uid])->save([
                'eyes_money' => ['exp', "eyes_money+{$coupon_num}"],
                'update_time' => date('Y-m-d H:i:s'),
            ]);
            if ($update === false) {
                throw new \Exception("发放护眼鲸币失败-1");
            }

            //插入任务记录
            $task_add = [
                'userid' => $uid,
                'taskid' => $task_id,
                'taskprice' => $task['taskprice'],
                'create_time' => date('Y-m-d H:i:s'),
                'record_date' => date('Y-m-d')
            ];
            $task_flag = M('eyes_task_log')->add($task_add);
            if(!$task_flag) throw new \Exception("发放护眼鲸币失败-2");

            //资金记录
            $add = [
                'userid' => $uid,
                'type' => 1,
                'typeid' => 2,
                'taskid' => 0,
                'change_money' => $coupon_num,
                'old_balance' => $user['eyes_money'],
                'new_balance' => $user['eyes_money']+$coupon_num,
                'create_time' => date('Y-m-d H:i:s'),
                'remarks' => $task['taskname']."获得{$task['taskprice']}",
            ];
            $flag = M('eyes_money_log')->add($add);
            if(!$flag) throw new \Exception("发放护眼鲸币失败");

            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }
    }



}